package com.crm.config;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;


/**自定义转换类
 * 	1、支持将字符串类型转成多种格式的日期格式
 *  2、需要ConversionServiceFactoryBean中注册，才能有效
 * @author SMILE
 *
 */
@Component
public class StringToDateConvert implements Converter<String, Date>{
	 //默认的日期格式
    String[] pattern = {"yyyy-MM-dd",
    					"yyyy-MM-dd HH:mm:ss.",
    					"yyyy年MM月dd日",
    					"HH时mm分ss秒",
    					"E MMM dd HH:mm:ss z yyyy,'Locale.US'",};
    SimpleDateFormat sdf = new SimpleDateFormat();
    
	@Override
	public Date convert(String source) {
		 System.out.println("自定义转换器——StringToDateConvert");
		 TimeZone.setDefault(TimeZone.getTimeZone("GMT+08"));
         Date date=null;
         int i=0;
         //遍历数组
         for(String p:pattern){
             //应用格式
             sdf.applyPattern(p);
             i++;
             try {
                  date=sdf.parse(source);
                  break;//转换成功，跳出循环
             } catch (Exception e) {
                  //如果当前格式转换失败，继续下一轮
                  continue;
             }
         }
         System.out.println("触发："+pattern[i]+"日期格式");
         if(date==null){
             throw new RuntimeException("日期转换失败！");
         }
         return date;
	}
	
    public void setPattern(String[] pattern) {
        this.pattern = pattern;
   }

}